package com.bosssoft.hr.train.j2se.collection;/*
 * @Auther:hantianbing
 * @Date:2022/12/2
 * @Description:ThreadArrayListDemo作业
 */

import lombok.Data;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @ClassName ThreadArrayListDemo
 * @Description 练习线程操作
 * @Author hantianbing
 * @Date 2022/12/2 22:53
 **/
@Slf4j
public class ThreadArrayListDemo {
    /**
     * 用于存数的list
     */
    protected static List<String> list = new ArrayList<>();

    public void startTest(){
        //包装一下，变成能同步的list
        List<String> syncProductList= Collections.synchronizedList(list);

        Thread producer = new Thread(new Producer(syncProductList));
        Thread consumer = new Thread(new Consumer(syncProductList));

        producer.start();
        consumer.start();
    }

}

/**
 * 生产者
 */
@Slf4j
class Producer implements Runnable{
    private static int num =0;

    private static int times = 10;

    private List<String> productList;

    public Producer(List<String> productList){
        this.productList = productList;
    }

    @Override
    public void run() {
        for(int i =0; i<times; i++){
            productList.add("苹果"+num);
            log.info("生产苹果第"+num+"号");
            num += 1;
            //休眠一秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

/**
 * 消费者
 */
@Slf4j
class Consumer implements Runnable{
    private static int times = 10;

    private List<String> productList;

    public Consumer(List<String> productList){
        this.productList = productList;
    }

    @Override
    public void run() {
        for (int i = 0; i < times; i++) {
            if (!productList.isEmpty()) {
                log.info("吃掉苹果: " + productList.get(0));
                productList.remove(0);
            }else{
                log.info("没有苹果可以吃");
            }
            //休眠一秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
